package com.gitee.fastmybatis.core.proxy;

import com.gitee.fastmybatis.core.util.IOUtil;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author 六如
 */
public class MapperProxy implements InvocationHandler {

    private static final Log LOG = LogFactory.getLog(MapperProxy.class);

    private final Class<?> mapperInterface;
    private final SqlSessionFactory sqlSessionFactory;

    public MapperProxy(Class<?> mapperInterface, SqlSessionFactory sqlSessionFactory) {
        this.mapperInterface = mapperInterface;
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        SqlSession session = sqlSessionFactory.openSession();
        Object mapper = session.getMapper(mapperInterface);
        try {
            Object result = method.invoke(mapper, args);
            session.commit();
            return result;
        } catch (Exception e) {
            session.rollback();
            LOG.error("Run mapper error, mapper class=" + proxy.getClass() + ", method=" + method, e);
            throw e;
        } finally {
            IOUtil.closeQuietly(session);
        }

    }
}
